<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.type" class="filter-item"  :clearable="false"
                 style="margin-left: 10px">
        <el-option
          v-for="item in [{ label: '年报', value: 'year'}, { label: '月报', value: 'month' },{ label: '日报', value: 'date' }]"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-date-picker
        style="margin-left: 20px;"
        class="filter-item"
        v-model="listQuery.date"
        :type="listQuery.type"
        :clearable="false"
        placeholder="选择时间">
      </el-date-picker>
      <el-button style="margin-left: 10px" class="filter-item" type="primary" icon="el-icon-plus"
                 @click="fetchData">
        查询
      </el-button>
      <el-button style="margin-left: 10px" v-if="checkPermission('扎帐')" class="filter-item" type="primary" icon="el-icon-plus"
                 @click="openCreateWindow">
        扎帐
      </el-button>
      <el-button  class="filter-item" icon="el-icon-download" :loading="btnLoading" style="margin-left:10px"
                  type="primary"
                  @click="handleExport">
        导出
      </el-button>
    </div>
    <div class="filter-container">
      <el-link href="#"  style="margin-left: 20px">累计营收：{{summaryAmount}} 元</el-link>
      <el-link href="#"  style="margin-left: 10px">实际营收：{{summaryRealAmount}} 元</el-link>
    </div>
    <el-divider/>
    <el-table
      key="late-fee-grid"
      ref="late-fee-grid"
      :loading="listLoading"
      :cell-style="{padding:0+'px'}"
      :data="list"
      :row-style="{height:40+'px'}"
      border
      fit
      height="700"
      highlight-current-row
      stripe
      style="width: 100%;"
    >
      <el-table-column
        type="index"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column align="center" label="账期">
        <template v-slot="{row}">
          <span>{{ formatDate(row.date)  }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="应收金额">
        <template v-slot="{row}">
          <span>{{ row.amount }}元</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="实收金额">
        <template v-slot="{row}">
          <span>{{ row.real_amount }}元</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="扎帐时间">
        <template v-slot="{row}">
          <span>{{ formatDate(row.created_at) }}</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :limit.sync="listQuery.pageSize" :page.sync="listQuery.page" :total="total"
                @pagination="fetchData"/>
    <el-dialog title="扎帐" :visible.sync="dialogCreateVisible"
               width="30%"
               custom-class="window-small-width"
               :close-on-click-modal="false">
      <el-form ref="createForm" :rules="createForm.rules" :model="createForm.model" :loading="formLoading"
               element-loading-spinner="el-icon-loading" label-position="right" label-width="100px">
        <el-form-item label="账期:" prop="name">
          <el-date-picker
            v-model="createForm.model.date"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择账期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="实收金额:" prop="method">
          <el-input v-model.number="createForm.model.real_amount"  />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCreateVisible = false">
          取消
        </el-button>
        <el-button :loading="btnLoading" type="primary" @click="handleSubmit">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {createRev,fetchRevList} from "@/api/finance";
import Pagination from '@/components/Pagination'
import {checkPermission} from "@/utils/permission";
import moment from "moment";
import {exportExcel} from "@/utils/excel";


export default {
  name: "LateFee",
  components: {Pagination},
  data() {
    return {
      dialogStatus:'create',
      listLoading: false,
      formLoading: false,
      btnLoading: false,
      summaryAmount: 0.00,
      summaryRealAmount: 0.00,
      dialogCreateVisible: false,
      listQuery: {
        type: 'date',
        pageSize: 20,
        date: null,
        page: 1
      },
      importData: {},
      list: [],
      files: [],
      total: 0,
      token: '',
      createForm: {
        rules: {
          date: [
            {required: true, message: '扎帐日期', trigger: 'blur'}
          ],
          real_amount: [
            {required: true, message: '实收金额', trigger: 'blur'}
          ]
        },
        model: {
          date: null,
          real_amount: null,
        }
      }
    }
  },
  filters: {
    statusText(val) {
      const t = ['已启用', '未启用']
      return t[val]
    },
    statusColor(val) {
      const t = ['default', 'upgrading', 'success', 'failed', 'cancel']
      return t[val]
    },
    paymentModelText(val) {
      const t = ['自出账后天开始计算', '每个月几号后开始计算']
      if(val.type === 1) {
        return '自出账后'+val.start_day+'天开始计算'
      }else {
        return '每月'+val.start_day+'号后开始计算'
      }
    },
    billText(val) {
      if(val.billing_type === 1) {
        return val.billing_value +'元'
      }else{
        return val.billing_value +'%'
      }
    }
  },
  created() {
    this.listQuery.date = moment().format('YYYY-MM-DD')
    this.fetchData()
  },
  methods: {
    checkPermission,
    fetchData() {
      if(this.listQuery.type === 'year'){
        this.listQuery.date = moment(this.listQuery.date).format('YYYY')
      }
      if(this.listQuery.type === 'month'){
        this.listQuery.date = moment(this.listQuery.date).format('YYYY-MM')
      }
      if(this.listQuery.type === 'date'){
        this.listQuery.date = moment(this.listQuery.date).format('YYYY-MM-DD')
      }
      this.listLoading = true

      fetchRevList(this.listQuery).then(res => {
        if (res.code === 20000) {
          this.list = res.data.list
          this.total = res.data.total.rows
          this.summaryAmount = res.data.total.amount
          this.summaryRealAmount = res.data.total.real_amount
        }
      }).catch(err => {
        this.$message.error(err)
      })
    },
    openCreateWindow() {
      this.dialogCreateVisible = true
      this.createForm.model = {
        date: null,
        real_amount: null,
      }
    },
    handleSubmit() {
      this.$refs['createForm'].validate((valid) => {
        if(valid) {
          createRev(this.createForm.model).then(resp => {
            if(resp.code === 20000) {
              this.$message.success('扎帐完成')
              this.dialogCreateVisible = false
              this.fetchData()
            }else {
              this.$message.error(resp.message)
            }
          })
        }
      });
    },
    formatDate(dateStr) {
      return moment(dateStr).format('YYYY-MM-DD')
    },
    handleExport() {
      if(this.listQuery.type === 'year'){
        this.listQuery.date = moment(this.listQuery.date).format('YYYY')
      }
      if(this.listQuery.type === 'month'){
        this.listQuery.date = moment(this.listQuery.date).format('YYYY-MM')
      }
      if(this.listQuery.type === 'date'){
        this.listQuery.date = moment(this.listQuery.date).format('YYYY-MM-DD')
      }
      this.listLoading = true

      fetchRevList(this.listQuery).then(res => {
        if (res.code === 20000) {
          const headers = ['用户','地址','表号','户号','付费模式','用水量','账单金额','账期','状态']
          const data = response.data.list.map(item => ({
            账期: this.formatDate(item.date),
            应收金额: item.amount,
            实收金额: item.real_amount,
            扎帐时间: this.formatDate(item.created_at),
          }))
          exportExcel(data, headers, '营收台账')
          setTimeout(() => {
            this.btnLoading = false
          }, 1.5 * 1000)
        }
      }).catch(err => {
        this.$message.error(err)
      })
    }
  }
}
</script>
